package com.xie.smfs.client.screen;
//驭鬼界面
import com.xie.smfs.common.events.PlayerEvents;
import com.xie.smfs.event.screen.GhostControlScreenHandler;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GhostControlScreen extends HandledScreen<GhostControlScreenHandler> {
    private static final Logger LOGGER = LoggerFactory.getLogger("smfs/GhostControlScreen");

    // 自定义背景纹理和槽位纹理
    private static final Identifier BACKGROUND_TEXTURE = new Identifier("smfs", "textures/gui/ghost_control_background.png");
    private static final Identifier SLOT_TEXTURE = new Identifier("smfs", "textures/gui/slot.png");

    // 界面尺寸
    private static final int TEXTURE_WIDTH = 176;
    private static final int TEXTURE_HEIGHT = 166;

    // 圆形分布参数
    private static final int CIRCLE_CENTER_X = 88;
    private static final int CIRCLE_CENTER_Y = 60;
    private static final int CIRCLE_RADIUS = 30;
    private static final int SLOT_SIZE = 18;
    private static final int SLOT_OFFSET = 8;

    // 属性显示参数 - 已调整以防止重叠
    private static final int ATTRIBUTE_LEFT_COLUMN = 0;
    private static final int ATTRIBUTE_RIGHT_COLUMN = 90;
    private static final int ATTRIBUTE_START_Y = 110;
    private static final int ATTRIBUTE_SPACING = 12;
    private static final int TEXT_COLOR = 0x404040;
    private static final int VALUE_COLOR = 0x000000;
    private static final int LABEL_WIDTH = 50;

    public GhostControlScreen(GhostControlScreenHandler handler, PlayerInventory inventory, Text title) {
        super(handler, inventory, title);
        this.backgroundWidth = TEXTURE_WIDTH;
        this.backgroundHeight = TEXTURE_HEIGHT;
        this.playerInventoryTitleY = -1000;
        LOGGER.info("灵异装备界面已创建");
    }

    @Override
    protected void init() {
        super.init();
        LOGGER.info("灵异装备界面初始化 - 尺寸: {}x{}", this.width, this.height);

        this.x = (this.width - this.backgroundWidth) / 2;
        this.y = (this.height - this.backgroundHeight) / 2;
    }

    @Override
    public void render(DrawContext context, int mouseX, int mouseY, float delta) {
        LOGGER.debug("界面开始渲染 - 鼠标位置: ({}, {})", mouseX, mouseY);
        this.renderBackground(context);
        super.render(context, mouseX, mouseY, delta);
        this.drawMouseoverTooltip(context, mouseX, mouseY);
    }

    @Override
    protected void drawBackground(DrawContext context, float delta, int mouseX, int mouseY) {
        LOGGER.debug("绘制背景 - delta: {}, 鼠标: ({}, {})", delta, mouseX, mouseY);

        // 绘制自定义背景纹理
        context.drawTexture(BACKGROUND_TEXTURE, this.x, this.y, 0, 0, this.backgroundWidth, this.backgroundHeight);

        // 绘制圆形分布的6个槽位
        drawGhostSlotsBackground(context);
    }

    // 修改绘制方法，确保使用最新数据
    private void drawGhostSlotsBackground(DrawContext context) {
        if (client == null || client.player == null) return;

        int centerX = this.x + CIRCLE_CENTER_X;
        int centerY = this.y + CIRCLE_CENTER_Y;

        LOGGER.debug("开始绘制槽位，玩家: {}", client.player.getName().getString());

        for (int i = 0; i < 6; i++) {
            double angle = 2 * Math.PI * i / 6;
            int x = centerX + (int)(CIRCLE_RADIUS * Math.cos(angle)) - SLOT_OFFSET;
            int y = centerY + (int)(CIRCLE_RADIUS * Math.sin(angle)) - SLOT_OFFSET;

            // 绘制槽位背景
            context.drawTexture(SLOT_TEXTURE, x, y, 0, 0, SLOT_SIZE, SLOT_SIZE, SLOT_SIZE, SLOT_SIZE);

            // 直接从 PlayerEvents 获取最新数据
            ItemStack itemStack = PlayerEvents.getGhostSlotItem(client.player, i);
            boolean isOccupied = PlayerEvents.isGhostSlotOccupied(client.player, i);

            LOGGER.debug("1.槽位 {}: occupied={}, item={}", i, isOccupied,
                    itemStack.isEmpty() ? "空" : itemStack.getItem().getName().getString());

            if (isOccupied && !itemStack.isEmpty()) {
                // 绘制物品图标
                context.drawItem(itemStack, x + 1, y + 1);
                context.drawItemInSlot(textRenderer, itemStack, x + 1, y + 1);

                // 绘制等级文本 - 在槽位之后绘制以避免遮挡，添加背景提高可读性
                int level = PlayerEvents.getGhostSlotLevel(client.player, i);
                String levelText = "Lv." + level;
                int textWidth = textRenderer.getWidth(levelText);

                // 添加半透明背景
                int bgPadding = 1;
                context.fill(x + (SLOT_SIZE - textWidth) / 2 - bgPadding,
                        y + SLOT_SIZE + 2 - bgPadding,
                        x + (SLOT_SIZE + textWidth) / 2 + bgPadding,
                        y + SLOT_SIZE + 2 + textRenderer.fontHeight + bgPadding,
                        0x80000000);

                context.drawText(textRenderer, levelText,
                        x + (SLOT_SIZE - textWidth) / 2,
                        y + SLOT_SIZE + 2,
                        0xFFFFFF, false);

                // 绘制复苏条
                drawSlotRevivalBar(context, x, y, i);
            }
        }
    }

    // 绘制槽位复苏条
    private void drawSlotRevivalBar(DrawContext context, int slotX, int slotY, int slotIndex) {
        if (client == null || client.player == null) return;

        NbtCompound ghostSlots = PlayerEvents.getGhostSlots(client.player);
        String slotKey = "Slot" + slotIndex;

        if (ghostSlots.contains(slotKey)) {
            NbtCompound slotData = ghostSlots.getCompound(slotKey);
            if (slotData.getBoolean("occupied")) {
                int revivalDegree = slotData.getInt("revivalDegree");
                int requiredRevivalDegree = slotData.getInt("requiredRevivalDegree");

                if (requiredRevivalDegree > 0) {
                    float progress = (float) revivalDegree / requiredRevivalDegree;
                    int barWidth = 16;
                    int barHeight = 2;
                    int barX = slotX + 1;
                    int barY = slotY + SLOT_SIZE - 3;

                    // 绘制复苏条背景
                    context.fill(barX, barY, barX + barWidth, barY + barHeight, 0xFF000000);

                    // 绘制复苏条前景
                    int progressWidth = (int) (barWidth * progress);
                    if (progressWidth > 0) {
                        context.fill(barX, barY, barX + progressWidth, barY + barHeight, 0xFF00FF00);
                    }
                }
            }
        }
    }

    // 获取玩家的鬼槽位数据
    private NbtCompound getGhostSlots(PlayerEntity player) {
        return PlayerEvents.getGhostSlots(player);
    }

    @Override
    protected void drawForeground(DrawContext context, int mouseX, int mouseY) {
        PlayerEntity player = this.client.player;
        if (player == null) return;

        // 使用辅助方法获取属性数据
        float spiritResistance = getSpiritAttribute(player, "spiritResistance", 0.0f);
        float spiritDamage = getSpiritAttribute(player, "spiritDamage", 0.0f);
        float currentSpirit = getSpiritAttribute(player, "currentSpirit", 0.0f);
        float maxSpirit = getSpiritAttribute(player, "maxSpirit", 0.0f);
        float revivalFactor = getSpiritAttribute(player, "revivalFactor", 0.0f);
        float sanity = getSpiritAttribute(player, "sanity", 100.0f);

        // 绘制左侧属性列
        drawAttributeText(context, "灵异抗性:", String.format("%.1f%%", spiritResistance),
                ATTRIBUTE_LEFT_COLUMN, ATTRIBUTE_START_Y);
        drawAttributeText(context, "灵异强度:", String.format("%.1f", maxSpirit),
                ATTRIBUTE_LEFT_COLUMN, ATTRIBUTE_START_Y + ATTRIBUTE_SPACING);
        drawAttributeText(context, "复苏因子:", String.format("%.1f%%", revivalFactor),
                ATTRIBUTE_LEFT_COLUMN, ATTRIBUTE_START_Y + ATTRIBUTE_SPACING * 2);

        // 绘制右侧属性列
        drawAttributeText(context, "灵异力量:", String.format("%.1f%%", spiritDamage),
                ATTRIBUTE_RIGHT_COLUMN, ATTRIBUTE_START_Y);
        drawAttributeText(context, "玩家理智:", String.format("%.1f", sanity),
                ATTRIBUTE_RIGHT_COLUMN, ATTRIBUTE_START_Y + ATTRIBUTE_SPACING);
    }

    // 辅助方法：获取灵异属性
    private float getSpiritAttribute(PlayerEntity player, String attributeName, float defaultValue) {
        try {
            NbtCompound spiritAttributes = PlayerEvents.getSpiritAttributes(player);
            if (spiritAttributes.contains(attributeName)) {
                // 先尝试以整数形式获取，再转换为float
                if (spiritAttributes.contains(attributeName, NbtElement.INT_TYPE)) {
                    return (float) spiritAttributes.getInt(attributeName);
                }
                // 否则尝试以float形式获取
                return spiritAttributes.getFloat(attributeName);
            } else {
                LOGGER.warn("属性 {} 未在NBT中找到，使用默认值: {}", attributeName, defaultValue);
            }
        } catch (Exception e) {
            LOGGER.error("获取灵异属性 {} 时出错: {}", attributeName, e.getMessage());
            LOGGER.warn("由于错误，属性 {} 使用默认值: {}", attributeName, defaultValue);
        }
        return defaultValue;
    }

    // 属性文本绘制辅助方法
    private void drawAttributeText(DrawContext context, String label, String value, int x, int y) {
        // 绘制标签（固定宽度，右对齐）
        int labelWidth = this.textRenderer.getWidth(label);
        context.drawText(this.textRenderer, Text.literal(label), x + LABEL_WIDTH - labelWidth, y, TEXT_COLOR, false);

        // 绘制值（左对齐）
        context.drawText(this.textRenderer, Text.literal(value), x + LABEL_WIDTH + 5, y, VALUE_COLOR, false);
    }

    @Override
    protected void drawMouseoverTooltip(DrawContext context, int x, int y) {
        super.drawMouseoverTooltip(context, x, y);

        // 添加槽位悬停提示
        if (client != null && client.player != null) {
            int centerX = this.x + CIRCLE_CENTER_X;
            int centerY = this.y + CIRCLE_CENTER_Y;

            for (int i = 0; i < 6; i++) {
                double angle = 2 * Math.PI * i / 6;
                int slotX = centerX + (int)(CIRCLE_RADIUS * Math.cos(angle)) - SLOT_OFFSET;
                int slotY = centerY + (int)(CIRCLE_RADIUS * Math.sin(angle)) - SLOT_OFFSET;

                // 检查鼠标是否在槽位上
                if (x >= slotX && x <= slotX + SLOT_SIZE && y >= slotY && y <= slotY + SLOT_SIZE) {
                    ItemStack itemStack = PlayerEvents.getGhostSlotItem(client.player, i);

                    if (!itemStack.isEmpty()) {
                        // 显示物品的原始提示信息
                        context.drawItemTooltip(textRenderer, itemStack, x, y);

                        // 添加额外的槽位信息
                        int level = PlayerEvents.getGhostSlotLevel(client.player, i);
                        NbtCompound ghostSlots = getGhostSlots(client.player);
                        String slotKey = "Slot" + i;

                        if (ghostSlots.contains(slotKey)) {
                            NbtCompound slotData = ghostSlots.getCompound(slotKey);
                            int revivalDegree = slotData.getInt("revivalDegree");
                            int requiredRevivalDegree = slotData.getInt("requiredRevivalDegree");

                            // 在原有提示基础上添加等级信息
                            Text levelInfo = Text.literal("等级: " + level + " | 复苏程度: " + revivalDegree + "/" + requiredRevivalDegree)
                                    .formatted(net.minecraft.util.Formatting.GRAY);
                            context.drawTooltip(textRenderer, levelInfo, x, y + 20);
                        }
                    } else {
                        context.drawTooltip(textRenderer, Text.literal("槽位 " + (i + 1) + " (空闲)"), x, y);
                    }
                    break;
                }
            }
        }
    }

    @Override
    public boolean shouldCloseOnEsc() {
        LOGGER.info("ESC键按下，准备关闭界面");
        return true;
    }

    @Override
    public void close() {
        LOGGER.info("界面开始关闭");
        if (this.client != null) {
            this.client.setScreen(null);
            LOGGER.info("客户端屏幕已设置为null");
        } else {
            LOGGER.warn("关闭界面失败: client为null");
        }
    }

    @Override
    protected boolean isClickOutsideBounds(double mouseX, double mouseY, int left, int top, int button) {
        return mouseX < (double)left ||
                mouseY < (double)top ||
                mouseX >= (double)(left + this.backgroundWidth) ||
                mouseY >= (double)(top + this.backgroundHeight);
    }

    // 在GhostControlScreen类中添加这些方法
    @Override
    public void handledScreenTick() {
        super.handledScreenTick();
        // 每 tick 检查数据更新
        if (client != null && client.player != null) {
            checkDataConsistency();
        }
    }

    private void checkDataConsistency() {
        // 检查服务器和客户端数据是否一致
        NbtCompound serverSlots = PlayerEvents.getGhostSlots(client.player);
        for (int i = 0; i < 6; i++) {
            ItemStack serverItem = PlayerEvents.getGhostSlotItem(client.player, i);
            boolean serverOccupied = PlayerEvents.isGhostSlotOccupied(client.player, i);

            LOGGER.debug("2.槽位 {} - 服务器: occupied={}, item={}",
                    i, serverOccupied, serverItem.isEmpty() ? "空" : serverItem.getItem().getName().getString());
        }
    }


}